package org.darkforest.merchant.interceptor;

import org.darkforest.model.Menu;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by chenyu on 15/1/29.
 * 拦截请求并对比菜单数据，赋值菜单定位索引
 */
public class MenuLocationInterceptor implements HandlerInterceptor {
    static final Logger logger = LoggerFactory.getLogger(MenuLocationInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
//        logger.debug("...." + request.getServletPath());
        String path = request.getServletPath();
        Integer pmenuIdx = 0;
        Integer smenuIdx = null;

        List<Menu> pmenu = (List<Menu>) request.getSession().getServletContext().getAttribute("pmenuList");
        List<List<Menu>> menuList = (List<List<Menu>>) request.getSession().getServletContext().getAttribute("menuList");
//        if(request.getSession().getAttribute("smenuIdx")!=null){
//            smenuIdx = (Integer)request.getSession().getAttribute("smenuIdx");
//        }
//        if(request.getSession().getAttribute("pmenuIdx")!=null){
//            smenuIdx = (Integer)request.getSession().getAttribute("pmenuIdx");
//        }
        boolean idxFlag = false;
        //如循环完毕仍未找到匹配的地址，说明在该页面内运行活动，地址不变
        while( pmenuIdx < pmenu.size() && smenuIdx==null){
            //主菜单链接匹配，子菜单定位在第一个
            if(path.indexOf(pmenu.get(pmenuIdx).getUrl())>0){
                smenuIdx = 0;
                idxFlag = true;
            }
            List<Menu> subMenuList = menuList.get(pmenuIdx);
            for (int s=0;s<subMenuList.size();s++){
                String menuName = subMenuList.get(s).getUrl();
                if (path.indexOf(menuName)>0){
                    smenuIdx = s;
                    //找到匹配的菜单即中止循环
                    idxFlag = true;
                    break;
                }
            }
            pmenuIdx++;
        }
        //父菜单，子菜单Idx赋值session级变量，页面匹配count数值(pmenuIdx在循环中已经+1需减去)
        if(idxFlag){
            request.getSession().setAttribute("smenuIdx",smenuIdx);
            request.getSession().setAttribute("pmenuIdx", pmenuIdx-1);
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
